package com.lwm.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 使用工厂生产Bean ---->从配置文件中读取（xml/properties）
 *
 * @author liweimin
 * @date 2021/6/1 17:55
 * @since
 */
public class BeanFactory {

    //定义一个properties对象
    private static Properties properties;

    //使用静态代码块初始化
    static {
        properties = new Properties();
        InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("初始化bean.properties");
        }
    }

    /**
     * 获取bean
     *
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        Object bean = null;
        String beanPath = properties.getProperty(beanName);
        try {
            //调用会创建新的实例对象
            bean = Class.forName(beanPath).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return bean;
    }

}
